<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
    <!-- 引入 layui.css -->
    <link href="//unpkg.com/layui@2.9.6/dist/css/layui.css" rel="stylesheet" />
    <style>
      .uploadArea {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 200px;
        height: 200px;
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <button type="button" class="btn btn-primary" id="add">添加</button>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">序号</th>
          <th scope="col">书名</th>
          <th scope="col">作者</th>
          <th scope="col">状态</th>
          <th scope="col">封面图</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <div id="tip"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
      crossorigin="anonymous"
    ></script>
    <!-- 引入 layui.js -->
    <script src="//unpkg.com/layui@2.9.6/dist/layui.js"></script>
    <script>
      const tobody = document.querySelector('tbody');
      const tipEle = document.getElementById('tip');
      const stateMap = {
        0: `<span style='color:red'>下架</span>`,
        1: `<span style='color:green'>上架</span>`,
      };
      //   初始化函数
      function init() {
        axios({
          method: 'get',
          url: `http://127.0.0.1:4500/getbook`,
        }).then((res) => {
          //   console.log(res.data);
          let str = '';
          if (res.data.length === 0) {
            tipEle.innerHTML = '暂无数据';
            tipEle.style.textAlign = 'center';
            tipEle.style.fontSize = '30px';
          }
          res.data.forEach((item, index) => {
            // console.log(item, index);
            console.log(item.cover);

            str += `<tr>
              <td>${index + 1}</td>
              <td>${item.bookName}</td>
              <td>${item.author}</td>
              <td>${stateMap[item.state]}</td>
              <td><img  style="width:50px" src=${
                item.cover
              } alt='暂无图片'/></td>
              <td>
                  <button type="button" class="btn btn-info" particulars='${
                    item.id
                  }'>详情</button>
                  <button type="button" class="btn btn-secondary" compile='${
                    item.id
                  }'>编辑</button>
                  <button type="button" class="btn btn-danger" del='${
                    item.id
                  }'>删除</button>
              </td>
            </tr>`;
          });
          tobody.innerHTML = str;
        });
      }
      init();

      //   添加
      const addBtn = document.getElementById('add');
      addBtn.addEventListener('click', () => {
        layer.open({
          type: 1,
          area: ['620px', '630px'], // 宽高
          content: `<form style='padding:20px' id='theForm'>
                            <div class="mb-3">
                                <label  class="form-label">书名</label>
                                <input type="text" class="form-control" name="bookName" autocomplete="off" >
                            </div>
                            <div class="mb-3">
                                <label  class="form-label">作者</label>
                                <input type="text" class="form-control" name="author" autocomplete="off">
                            </div>
                            <div class="mb-3">
                                <label  class="form-label">状态</label>
                                <input class="form-check-input" type="radio" name="state" value='1' checked>上架
                                <input class="form-check-input" type="radio" name="state" value='0'>下架
                            </div>
                            <div class="mb-3">
                                <label  class="form-label">添加封面图</label>
                                <input type="file" class="form-control" id="file" name='cover' autocomplete="off" style='display:none'>
                                <div id='uploadArea' class='uploadArea'>上传文件 </div>
                            </div>
                            <div class="mb-3">
                                <img id='previewImg' style='width:200px'/>
                            </div>
                            <button type="button" class="btn btn-primary" id='addbook'>添加</button>
                    </form>  `,
        });
        const addbook = document.getElementById('addbook');
        const previewImg = document.getElementById('previewImg');
        const fileEle = document.getElementById('file');
        const uploadAreaEle = document.getElementById('uploadArea');
        const theFormEle = document.getElementById('theForm');

        // // 上传文件区域
        uploadAreaEle.addEventListener('click', () => {
          fileEle.click();
        });
        previewImg.addEventListener('click', () => {
          fileEle.click();
        });
        // // 预览
        let file;
        fileEle.addEventListener('change', async () => {
          uploadAreaEle.style.display = 'none';
          file = fileEle.files[0];
          //   console.log(file);
          if (file) {
            let imgURL = URL.createObjectURL(file);
            previewImg.src = imgURL;
          }
        });
        addbook.addEventListener('click', async () => {
          let formData = new FormData(theFormEle);
          console.log(formData);
          let { data } = await axios({
            method: 'post',
            url: 'http://127.0.0.1:4500/addbook',
            data: formData,
          });
          let { code, message } = data;
          if (code === 20000) {
            layer.msg(message);
          } else {
            layer.msg(message);
          }
          setTimeout(() => {
            init();
            location.reload();
          }, 500);
        });
      });
      //   操作
      tobody.addEventListener('click', (event) => {
        let delId = event.target.getAttribute('del');
        let compileId = event.target.getAttribute('compile');
        if (delId) {
          if (confirm('确定删除？')) {
            del(delId);
          }
        }
        if (compileId) {
          compile(compileId);
        }
      });
      //   删除函数
      async function del(delId) {
        let { data } = await axios({
          method: 'delete',
          url: `http://127.0.0.1:4500/deletebook?id=${delId}`,
        });
        let { code, message } = data;
        if (code === 20000) {
          layer.msg(message);
        } else {
          layer.msg(message);
        }
        init();
      }
      //编辑函数
      async function compile(compileId) {
        let { data } = await axios({
          method: 'get',
          url: `http://127.0.0.1:4500/getOnebook/${compileId}`,
        });
        console.log(data);
        let { bookName, author, state, cover } = data;
        layer.open({
          type: 1,
          area: ['620px', '630px'], // 宽高
          content: `<form style='padding:20px' id='theForm'>
                            <div class="mb-3">
                                <label  class="form-label">书名</label>
                                <input type="text" class="form-control" id="bookName" name="bookName" autocomplete="off"  >
                            </div>
                            <div class="mb-3">
                                <label  class="form-label">作者</label>
                                <input type="text" class="form-control" id="author" name="author" autocomplete="off">
                            </div>
                            <div class="mb-3">
                                <label  class="form-label">状态</label>
                                <input class="form-check-input" type="radio" name="state" ${
                                  state === 1 ? 'checked' : ''
                                } value='1' >上架
                                <input class="form-check-input" type="radio" name="state" ${
                                  state === 0 ? 'checked' : ''
                                } value='0'>下架
                            </div>
                            <div class="mb-3">
                                <label  class="form-label">添加封面图</label>
                                <input type="file" class="form-control" id="file" name='cover' autocomplete="off" style='display:none'>
                                <div id='uploadArea' class='uploadArea'>上传文件 </div>
                            </div>
                            <div class="mb-3">
                                <img id='previewImg' style='width:200px'/>
                            </div>
                            <button type="button" class="btn btn-primary" id='putbook'>编辑</button>
                    </form>  `,
        });
        document.getElementById('bookName').value = bookName;
        document.getElementById('author').value = author;

        const putbook = document.getElementById('putbook');
        const previewImg = document.getElementById('previewImg');
        const fileEle = document.getElementById('file');
        const uploadAreaEle = document.getElementById('uploadArea');
        const theFormEle = document.getElementById('theForm');
        console.log(cover);
        // // 上传文件区域
        if (cover) {
          uploadAreaEle.style.display = 'none';
          previewImg.src = `${cover}`;
          previewImg.addEventListener('click', () => {
            fileEle.click();
          });
        } else {
          uploadAreaEle.style.display = '';
          uploadAreaEle.addEventListener('click', () => {
            uploadAreaEle.style.display = 'none';
            fileEle.click();
          });
        }
        // 预览
        let file;
        fileEle.addEventListener('change', async () => {
          uploadAreaEle.style.display = 'none';
          file = fileEle.files[0];
          //   console.log(file);
          if (file) {
            let imgURL = URL.createObjectURL(file);
            previewImg.src = imgURL;
          }
        });

        putbook.addEventListener('click', async () => {
          let formData = new FormData(theFormEle);
          console.log(formData);
          let { data } = await axios({
            method: 'put',
            url: `http://127.0.0.1:4500/putbook?id=${compileId}`,
            data: formData,
          });
          let { code, message } = data;
          if (code === 20000) {
            layer.msg(message);
          } else {
            layer.msg(message);
          }
          setTimeout(() => {
            init();
            location.reload();
          }, 500);
        });
      }
    </script>
  </body>
</html>
